module(...,package.seeall)

local decoratorsystem_mt = {
    __index = function(t,k)
      return getmetatable(t)[k]
    end,
    get = function (self,t,k,v)
        -->foreach decorator modify v, decorators need to be permutable functions
        local i,d
        for i,d in pairs(self.decorators) do
          if d.__calls["get_"..k] then
            printd("Value for ".. k .." decorated by ",d)
            v = d.__calls["get_"..k](d,t,v) 
          end
        end
        return v
    end,
    set = function (self,t,k,v)
        -->foreach decorator modify v, decorators need to be permutable functions
        local i,d
        for i,d in pairs(self.decorators) do
          if d.__calls["set_"..k] then
            printd("Value for ".. k .." decorated by ",d)
            v = d.__calls["set_"..k](d,t,v) 
          end
        end
        return v
    end,
}

new = function(name,t)
  local d = {}
  d.__name = name
  d.__calls = t
  return d--readonly(d)
end

newsystem = function(t)
  local ds = {}
  ds.decorators = t or {}
  setmetatable(ds,decoratorsystem_mt)
  return ds
end

if __UNIT_TEST__ then
  unittest.start()
  
    testdecorator = new("testdecorator",{
      get_price = function(self,target,v)
        return v/2
      end,
      set_price = function(self,target,v)
        return v
      end,
      get_cost = function(self,target,v)
        return v/4
      end,
      set_cost = function(self,target,v)
        return v
      end,
      get_value = function(self,target,v)
        return "priceless"
      end,
      set_value = function(self,target,v)
        return  v
      end,  
    })
    
    ds = newsystem{
      testdecorator,
    }
    
  unittest.stop()
end
